package com.zyy.rabbitmq.service;

import com.zyy.rabbitmq.pojo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

/**
 * @Description: 类描述
 * @Author: zyy
 * @Date: 2023/06/03 22:45
 */
@Service
public class OrderService {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private MQOrderService mqOrderService;

    @Transactional(rollbackFor = Exception.class)
    public void createOrder(Order order) throws Exception {
        //先创建订单
        saveOrder(order);

        //然后调用远程服务，创建运单
        String result = dispatcherHttpApi(order.getOrderId());
        if (!"success".equals(result)) {
            throw new Exception("创建运单失败");
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void createOrderMessage(Order order) throws Exception {
        //先创建订单 并且冗余一份
        saveOrder(order);
        saveOrderMessage(order);
        //mq推送给运单
        mqOrderService.sendMessage(order);
    }

    public void saveOrder(Order order) throws Exception {
        String sql = "insert into `order`(order_id, user_id, order_content, create_time) values(?,?,?,?)";

        int count = jdbcTemplate.update(sql, order.getOrderId(),
                order.getUserId(), order.getOrderContent(), order.getCreateTime());
        if (count != 1) {
            throw new Exception("订单创建失败！");
        }
    }

    public void saveOrderMessage(Order order) throws Exception {
        String sql = "insert into `order_message`(order_id, user_id, order_content, status, create_time) values(?,?,?,?,?)";

        int count = jdbcTemplate.update(sql, order.getOrderId(),
                order.getUserId(), order.getOrderContent(), "0", order.getCreateTime());
        if (count != 1) {
            throw new Exception("订单冗余失败！");
        }
    }

    private String dispatcherHttpApi(Integer orderId) {
        SimpleClientHttpRequestFactory httpRequestFactory = new SimpleClientHttpRequestFactory();
        //连接超时时间  milliseconds
        httpRequestFactory.setConnectTimeout(3000);
        //处理超时时间
        httpRequestFactory.setReadTimeout(2000);

        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);

        String url = "http://localhost:9000/dispatcher/create?orderId=" + orderId;

        return restTemplate.getForObject(url, String.class);

    }
}
